package com.user_service.util;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

@Component
public class JwtUtil {
    
    // 密钥--从配置文件中获取
    @Value("${jwt.secret}")
    private String secret;
    
    // 过期时间--从配置文件中获取
    @Value("${jwt.expiration:3600}")
    private Long expiration;
    
    private SecretKey getSigningKey() {
        // 验证密钥是否配置
        if (secret == null || secret.trim().isEmpty()) {
            throw new IllegalStateException("JWT secret key is not configured. Please set jwt.secret in application.yml");
        }
        
        if (secret.length() < 64) {
            // 密钥太短，记录警告
            System.out.println("Warning: JWT secret key is too short. For HS512 algorithm, recommended length is at least 64 characters.");
        }
        
        return Keys.hmacShaKeyFor(secret.getBytes());
    }
    
    /**
     * 从token中获取用户名
     */
    public String getUsernameFromToken(String token) {
        return getClaimFromToken(token, Claims::getSubject);
    }
    
    /**
     * 从token中获取用户ID
     */
    public Long getUserIdFromToken(String token) {
        String userId = getClaimFromToken(token, claims -> claims.getSubject());
        return Long.parseLong(userId);
    }
    
    /**
     * 从token中获取过期时间
     */
    public Date getExpirationDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getExpiration);
    }
    
    public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.apply(claims);
    }
    
    /**
     * 解析token
     */
    private Claims getAllClaimsFromToken(String token) {
        token = removeBearerPrefix(token);
        return Jwts.parserBuilder().setSigningKey(getSigningKey()).build().parseClaimsJws(token).getBody();
    }
    
    /**
     * 移除Bearer前缀
     */
    private String removeBearerPrefix(String token) {
        if (token != null && token.startsWith("Bearer ")) {
            return token.substring(7);
        }
        return token;
    }
    
    /**
     * 检查token是否过期
     */
    private Boolean isTokenExpired(String token) {
        final Date expiration = getExpirationDateFromToken(token);
        return expiration.before(new Date());
    }
    
    /**
     * 生成token
     */
    public String generateToken(Long userId) {
        Map<String, Object> claims = new HashMap<>();
        return doGenerateToken(claims, userId.toString());
    }
    
    /**
     * 生成token的实际方法
     */
    private String doGenerateToken(Map<String, Object> claims, String subject) {
        final Date createdDate = new Date();
        final Date expirationDate = new Date(createdDate.getTime() + expiration * 1000);
        
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(createdDate)
                .setExpiration(expirationDate)
                .signWith(getSigningKey(), SignatureAlgorithm.HS512)
                .compact();
    }
    
    /**
     * 验证token
     */
    public Boolean validateToken(String token, Long userId) {
        try {
            final String userIdFromToken = getUsernameFromToken(token);
            return (userIdFromToken.equals(userId.toString()) && !isTokenExpired(token));
        } catch (Exception e) {
            return false;
        }
    }
}